package com.m7788.screen;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.m7788.po.UploadInfo;
import com.m7788.po.UploadProData;
import com.m7788.util.AppUtil;
import com.m7788.util.Constant;
import com.m7788.util.ImageUpload;
import com.m7788.view.UmengBaseActivity;
import com.tool.utils.DBUtil;

public class CustomCamera extends UmengBaseActivity implements OnClickListener,
		SurfaceHolder.Callback, PictureCallback {
	public static final int LARGEST_WIDTH = 400;
	public static final int LARGEST_HEIGHT = 800;
	TextView tip;
	SurfaceView cameraView;
	Button btn_left, btn_right;
	SurfaceHolder surfaceHolder;

	Camera gCamera;
	Uri imageFileUri;
	private String type;// 动作类型
	private String params;// 参数集合
	Map<String, String> parmasMap;
	private String Oper;// 判断来源
	private String wapFrom;
	ArrayList<UploadInfo> infoList;
	UploadProData proData;
	int canTemp = 0;
	int curing = 0;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 横向模式显示
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
//				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.take_photo_sufview);
		tip = (TextView) this.findViewById(R.id.tps_tv_tip);
		btn_left = (Button) this.findViewById(R.id.tps_btn_left);
		btn_left.setOnClickListener(this);
		btn_right = (Button) this.findViewById(R.id.tps_btn_right);
		btn_right.setOnClickListener(this);
		cameraView = (SurfaceView) this.findViewById(R.id.CameraView);
		cameraView.setFocusable(true);
		cameraView.setFocusableInTouchMode(true);
		cameraView.setClickable(true);
		cameraView.setOnClickListener(this);
		surfaceHolder = cameraView.getHolder();
		surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		surfaceHolder.addCallback(this);

	}

	@Override
	protected void onDestroy() {
		surfaceDestroyed(null);
		super.onDestroy();
	}

	private void initDBdata() {
		Oper = AppUtil.getRecord(CustomCamera.this,Constant.OPERATION);
		type = AppUtil.getRecord(CustomCamera.this,Constant.TYPE);
		params = AppUtil.getRecord(CustomCamera.this,Constant.PARAMS);
		wapFrom = AppUtil.getRecord(CustomCamera.this,Constant.FROM);
		if (params.length() > 0) {
			parmasMap = AppUtil.combineHttpParams(params);
		}
	}

	public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {

	}

	public void surfaceCreated(SurfaceHolder holder) {
		gCamera = Camera.open();
		initDBdata();
		try {
			Camera.Parameters parameters = gCamera.getParameters();
			if(parameters!=null){
				if (this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
					// 这是一个众所周知但未文档化的特性
					parameters.set("orientation", "portrait");
					String sdk = Build.VERSION.SDK;
					Integer sdkInt = Integer.valueOf(sdk);
					if (sdkInt > 7) {
						gCamera.setDisplayOrientation(90);
						parameters.setRotation(90);
					}
					// 对于Android 2.2及以上版本
					// gCamera.setDisplayOrientation(90);
					// 对于Android 2.2及以上版本取消注释
					// parameters.setRotation(90);

				} else {
					// 这是一个众所周知但未文档化的特性
					parameters.set("orientation", "landscape");
					String sdk = Build.VERSION.SDK;
					Integer sdkInt = Integer.valueOf(sdk);
					if (sdkInt > 7) {
						gCamera.setDisplayOrientation(0);
						parameters.setRotation(0);
					}
					// 对于Android 2.2及以上版本
					// gCamera.setDisplayOrientation(0);
					// 对于Android 2.2及以上版本取消注释
					// parameters.setRotation(0);

				}
				int bestWidth = 300;
				int bestHeight = 300;

				List<Camera.Size> supportSizes = parameters
						.getSupportedPictureSizes();
				List<Camera.Size> previewSizes = parameters
						.getSupportedPreviewSizes();
				if (previewSizes.size() > 1) {
					Iterator<Camera.Size> cei = previewSizes.iterator();
					while (cei.hasNext()) {
						Camera.Size aSize = cei.next();

						// 如果该列表中的当前大小大于保存的最佳大小，
						// 并且小于或等于LARGEST_WIDTH和LARGEST_HEIGHT常量，
						// 那么将在bestWidth和bestHeight变量中保存这个高度和宽度并继续检查。

						// Log.e("previews","Checking " + aSize.width + " x "+
						// aSize.height);

						if (aSize.width > bestWidth || aSize.height > bestHeight) {
							// 迄今为止，它是最大的大小，且不超过屏幕尺寸
							bestWidth = aSize.width;
							bestHeight = aSize.height;
						}

					}
				}

				int v = 0;

				int bestSWidth = 0;
				int bestSHeight = 0;

				int bestSWidth_1000 = 1300;
				int bestSHeight_1000 = 1300;

				int bestSWidth_2000 = 2600;
				int bestSHeight_2000 = 2600;

				int bestSWidth_4000 = 5200;
				int bestSHeight_4000 = 5200;

				int bestSWidth_max = 0;
				int bestSHeight_max = 0;

				if (supportSizes.size() > 1) {
					Iterator<Camera.Size> cei = supportSizes.iterator();
					while (cei.hasNext()) {
						Camera.Size aSize = cei.next();

						// 如果该列表中的当前大小大于保存的最佳大小，
						// 并且小于或等于LARGEST_WIDTH和LARGEST_HEIGHT常量，
						// 那么将在bestWidth和bestHeight变量中保存这个高度和宽度并继续检查。

						Log.e("support", "Checking " + aSize.width + " x "
								+ aSize.height);

						if (aSize.width > aSize.height) {
							v = aSize.width;

							if (v > 1000 && v < 1300
									&& bestSWidth_1000 > aSize.width) {
								bestSWidth_1000 = aSize.width;
								bestSHeight_1000 = aSize.height;
							}

							if (v == bestSWidth_1000
									&& aSize.height > bestSHeight_1000) {
								bestSHeight_1000 = aSize.height;
							}

							if (v > 2000 && v < 2600
									&& bestSWidth_2000 > aSize.width) {
								bestSWidth_2000 = aSize.width;
								bestSHeight_2000 = aSize.height;
							}

							if (v == bestSWidth_2000
									&& aSize.height > bestSHeight_2000) {
								bestSHeight_2000 = aSize.height;
							}

							if (v > 4000 && v < 5200
									&& bestSWidth_4000 > aSize.width) {
								bestSWidth_4000 = aSize.width;
								bestSHeight_4000 = aSize.height;
							}

							if (v == bestSWidth_4000
									&& aSize.height > bestSHeight_4000) {
								bestSHeight_4000 = aSize.height;
							}

							if (bestSWidth_max < aSize.width) {
								bestSWidth_max = aSize.width;
								bestSHeight_max = aSize.height;
							}

							if (v == bestSWidth_max
									&& aSize.height > bestSHeight_max) {
								bestSHeight_max = aSize.height;
							}
						} else {
							v = aSize.height;
							if (v > 1000 && v < 1300
									&& bestSHeight_1000 > aSize.height) {
								bestSWidth_1000 = aSize.width;
								bestSHeight_1000 = aSize.height;
							}

							if (v == bestSHeight_1000
									&& aSize.width > bestSWidth_1000) {
								bestSWidth_1000 = aSize.width;
							}

							if (v > 2000 && v < 2600
									&& bestSHeight_2000 > aSize.height) {
								bestSWidth_2000 = aSize.width;
								bestSHeight_2000 = aSize.height;
							}

							if (v == bestSHeight_2000
									&& aSize.width > bestSWidth_2000) {
								bestSWidth_2000 = aSize.width;
							}

							if (v > 4000 && v < 5200
									&& bestSHeight_4000 > aSize.height) {
								bestSWidth_4000 = aSize.width;
								bestSHeight_4000 = aSize.height;
							}

							if (v == bestSHeight_4000
									&& aSize.width > bestSWidth_4000) {
								bestSWidth_4000 = aSize.width;
							}

							if (bestSHeight_max < aSize.height) {
								bestSWidth_max = aSize.width;
								bestSHeight_max = aSize.height;
							}

							if (v == bestSHeight_max
									&& aSize.width > bestSWidth_max) {
								bestSWidth_max = aSize.width;
							}
						}
					}

					if (bestSWidth_1000 < 1300) {
						bestSWidth = bestSWidth_1000;
						bestSHeight = bestSHeight_1000;
					}

					if (bestSWidth_1000 == 1300 && bestSWidth_2000 < 2600) {
						bestSWidth = bestSWidth_2000;
						bestSHeight = bestSHeight_2000;
					}

					if (bestSWidth_1000 == 1300 && bestSWidth_2000 == 2600
							&& bestSWidth_4000 < 5200) {
						bestSWidth = bestSWidth_4000;
						bestSHeight = bestSHeight_4000;
					}

					if (bestSWidth_1000 == 1300 && bestSWidth_2000 == 2600
							&& bestSWidth_4000 == 5200 && bestSWidth_max > 0) {
						bestSWidth = bestSWidth_max;
						bestSHeight = bestSHeight_max;
					}

					Log.e("support", "bestSWidth_1000= " + bestSWidth_1000
							+ " bestSHeight_1000= " + bestSHeight_1000);
					Log.e("support", "bestSWidth_2000= " + bestSWidth_2000
							+ " bestSHeight_2000= " + bestSHeight_2000);
					Log.e("support", "bestSWidth_4000= " + bestSWidth_4000
							+ " bestSHeight_4000= " + bestSHeight_4000);
					Log.e("support", "bestSWidth_max= " + bestSWidth_max
							+ " bestSHeight_max= " + bestSHeight_max);
					Log.e("support", "bestSWidth= " + bestSWidth + " bestSHeight= "
							+ bestSHeight);
				}
				WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);// 得到窗口管理器
				Display display = wm.getDefaultDisplay();// 得到当前屏幕
				parameters.setPreviewSize(bestWidth, bestHeight);// 设置尺寸
				parameters.setPictureSize(bestSWidth, bestSHeight);
				parameters.setPictureFormat(PixelFormat.JPEG);
				// 设置自动触发闪光灯
				// parameters.setFlashMode(Camera.Parameters.FLASH_MODE_AUTO);
				parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF); // 关闭自动闪光灯
				// parameters.setFocusMode();;
				gCamera.setParameters(parameters);
			}
			gCamera.setPreviewDisplay(holder);
		} catch (IOException exception) {
			gCamera.release();
		}

		// 最后，启动摄像头预览。
		gCamera.startPreview();
	}

	public void surfaceDestroyed(SurfaceHolder holder) {
		if(gCamera!=null){
			gCamera.setPreviewCallback(null);
			gCamera.stopPreview();
			gCamera.release();
			gCamera = null;
		}
	}

	@Override
	public void onPictureTaken(byte[] data, Camera arg1) {
		// 保存到系统默认地址
		imageFileUri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI,
				new ContentValues());
		try {
			OutputStream imageFileOS = getContentResolver().openOutputStream(
					imageFileUri);
			imageFileOS.write(data);
			imageFileOS.flush();
			imageFileOS.close();
		} catch (FileNotFoundException e) {
			Toast t = Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT);
			t.show();
		} catch (IOException e) {
			Toast t = Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT);
			t.show();
		}

		gCamera.startPreview();

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.tps_btn_left:
			finish();
			break;
		case R.id.tps_btn_right:
			btn_right.setText("正在处理");
			btn_right.setTextColor(Color.GRAY);
			// gCamera.cancelAutoFocus();
			new Handler().postDelayed(new Runnable() {
				@Override
				public void run() {
					if(gCamera!=null){
						gCamera.autoFocus(new AutoFoucus()); // 自动对焦
					}
				}
			},100);

		default:
			btn_right.setText("正在处理");
			btn_right.setTextColor(Color.GRAY);
			new Handler().postDelayed(new Runnable() {
				@Override
				public void run() {
					if(gCamera!=null){
						gCamera.autoFocus(new AutoFoucus()); // 自动对焦
					}
				}
			},100);

		}

	}

	private final class AutoFoucus implements AutoFocusCallback {
		@Override
		public void onAutoFocus(boolean success, Camera camera) {
			if (success && camera != null) {
				// camera.takePicture(mShutterCallback, null, mPictureCallback);
				gCamera.setOneShotPreviewCallback(previewCallback);
			} else {
				Toast t = Toast.makeText(CustomCamera.this, "对焦失败，请重新拍摄",
						Toast.LENGTH_SHORT);
				t.show();
				btn_right.setText("拍照");
				btn_right.setTextColor(Color.WHITE);
			}
		}
	}

	private final PictureCallback mPictureCallback = new PictureCallback() {
		@Override
		public void onPictureTaken(byte[] data, Camera camera) {
			// savePhoto(data);
			SaveThread st = new SaveThread(data, CustomCamera.this);
			st.start();
		}
	};

	private final ShutterCallback mShutterCallback = new ShutterCallback() {
		/**
		 * 在相机快门关闭时候的回调接口，通过这个接口来通知用户快门关闭的事件，
		 * 普通相机在快门关闭的时候都会发出响声，根据需要可以在该回调接口中定义各种动作， 例如：使设备震动
		 */
		public void onShutter() {
		}
	};

	private Camera.PreviewCallback previewCallback = new Camera.PreviewCallback() {
		@Override
		public void onPreviewFrame(byte[] data, Camera arg1) {
			gCamera.takePicture(mShutterCallback, null, mPictureCallback);
		}
	};

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_CAMERA) { // 按下相机实体按键，启动本程序照相功能
			gCamera.autoFocus(new AutoFoucus()); // 自动对焦
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}

	public String getRealPathFromURI(Uri contentUri) {
		String[] proj = { Media.DATA };
		Cursor cursor = managedQuery(contentUri, proj, null, null, null);
		int column_index = cursor
				.getColumnIndexOrThrow(Media.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	}

	class SaveThread extends Thread {
		private byte[] pdata;
		private Context mcontext;

		public SaveThread(byte[] pdata, Context mcontext) {
			this.pdata = pdata;
			this.mcontext = mcontext;
		}

		@Override
		public void run() {

			FileOutputStream b = null;
			try {
				// 保存到系统默认DCIM下
				// imageFileUri =
				// getContentResolver().insert(Media.EXTERNAL_CONTENT_URI,
				// new ContentValues());
				// OutputStream imageFileOS =
				// getContentResolver().openOutputStream(imageFileUri);
				// imageFileOS.write(pdata);
				// imageFileOS.flush();
				// imageFileOS.close();
				// String imagePath = getRealPathFromURI(imageFileUri);

				// 保存到自定义路径
				if (!new File(Environment.getExternalStorageDirectory()
						.getAbsolutePath() + File.separator + "7788").exists()) {
					new File(Environment.getExternalStorageDirectory()
							.getAbsolutePath() + File.separator + "7788")
							.mkdirs();
				}
				String imagePath = Environment.getExternalStorageDirectory()
						.getAbsolutePath()
						+ File.separator
						+ "7788"
						+ File.separator + new Date().getTime() + ".jpg";
				b = new FileOutputStream(imagePath);
				b.write(pdata);
				b.flush();
				b.close();
			    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2) {
                    Intent mediaScanIntent = new Intent(
                            Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                    Uri contentUri = Uri.fromFile(new File(imagePath)); //out is your output file
                    mediaScanIntent.setData(contentUri);
                    sendBroadcast(mediaScanIntent);
                } else {
                	sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"    
		                    + Environment.getExternalStorageDirectory())));    
                }
				// Log.e("CustomCamera", imagePath);
				// int degree = AppUtil.readPictureDegree(imagePath);
				AppUtil.saveRecord(mcontext, Constant.SinglePhoto, imagePath);
				// AppUtil.saveRecord(mcontext, Constant.SINGLE_DEGREE,
				// ""+degree);
				Intent intent = new Intent(mcontext, SinglePhotoScreen.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

				startActivity(intent);
				finish();
			} catch (FileNotFoundException e) {
			} catch (IOException e) {
			} finally {
				pdata = null;
			}
		}
	}

}